﻿<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage/NoRightAd.Master" AutoEventWireup="true" 
    CodeBehind="UploadPhotoAsync.aspx.cs" Inherits="Foothill.Web.UploadPhotoAsync" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    <link rel="stylesheet" href="post-common.css" type="text/css" />
    <link rel="stylesheet" href="uploadAsync.css" type="text/css" />
    
    <script type="text/javascript">
        var MAX_NUM_PHOTOS = 16;
        var BlankImageSrc = '../Images/space.gif';
        var firstUpload = true;

        var photoShowcases = new Array(); 
        
        function isImageEmpty(currentImage) {
            return currentImage === '' || currentImage == null || currentImage == BlankImageSrc;
        }

        function getProgressId(index)
        {
            index++;
            return "prog-" + index;
        }

        function getRemoveButtonId(index) {
            index++;
            return "imgBtn-" + index;
        }

        function initShowcases() {
            for (var i = 0; i < MAX_NUM_PHOTOS; ++i) {
                var showcase = {
                    index: i,
                    hasImage: false
                };

                photoShowcases[i] = showcase;
            }
        }

        $(document).ready(function () {
            initShowcases();

            $('div.showcase').droppable({
                accept: 'img.upload-img',
                hoverClass: "ui-state-active",
                drop: handleCarDrop,
                over: dragOver,
                out: dragOut
            });

            $('img.upload-img').attr('src', BlankImageSrc);
            $('img.upload-img').draggable({ revert: true, zIndex: 99, cursor: "move" });

            $('.upload-progress').hide();

            $('span.del-span').hide();
            $('span.del-span').click(function () {
                var div = $(this).parent();
                removeUploadedPhoto(div);
            });

            $('#btnSubmit').click(submit);
        });

        function getAvailableShowcase() {
            var showcase;         
            var foundAvailable = false;
            
            for (var i = 0; i < MAX_NUM_PHOTOS; ++i) {
                showcase = photoShowcases[i];

                if (!showcase.hasImage) {
                    foundAvailable = true;
                    break;
                }
            }

            if (!foundAvailable) {
                showcase = null;
            }
            
            return showcase;
        }

        function processFiles(files) {         
            if (firstUpload) {
                clearCurrentPhotoList();
                firstUpload = false;
            }

            for (var i = 0; i < files.length; i++) {
                var showcase = getAvailableShowcase();

                if (showcase != null) {
                    sendFile(files[i], showcase);
                }
            }
        }

        function clearCurrentPhotoList() {
            $.ajax({
                type: "POST",
                url: "UploadPhotoAsync.aspx/ClearCurrentPhotoListInSession",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });
        }

        function sendFile(file, showcase) {
            var xhr = new XMLHttpRequest();

            showcase.hasImage = true;
            xhr.showcaseIndex = showcase.index;

            var data = new FormData();

            data.append(file.name, file);

            xhr.onreadystatechange = function () {
                if (xhr.readyState == 2) {
                    $('#' + getProgressId(showcase.index)).show();
                }
            }

            xhr.addEventListener('load', function (evt) {
                var obj = JSON.parse(evt.target.responseText);
                showcase.hasImage = true;
                displayUploadedPhoto(obj.PhotoFileName, showcase.index);
                $('#' + getProgressId(showcase.index)).hide(); 
            }, false);

            xhr.addEventListener('error', function OnError(evt) {
                showcase.hasImage = false;
                alert('Error Uploading File(s)!');
            }, false);

            xhr.open('POST', 'UploadPhotoHandler.ashx', true);
            xhr.send(data);
        }

        function displayUploadedPhoto(fileName, index) {
            var imageUrl = "../upload_thumbnail/" + fileName;

            index++;
            $('#imgBtn-' + index).css('display', 'inline');
            $('#img-' + index).attr("src", imageUrl);
        }

        function extractFilename(imgUrl) {
            var fileNameIndex = imgUrl.lastIndexOf("/") + 1;
            var filename = imgUrl.substr(fileNameIndex);
            return filename;
        }

        function removeUploadedPhoto(div) {
            var img = div.find('img.upload-img');
            var imgUrl = img.attr('src');

            if (!isImageEmpty(imgUrl)) {
                var filename = extractFilename(imgUrl);
                filename = filename.substring(0, filename.lastIndexOf('.'));

                $.ajax({
                    type: "POST",
                    url: "UploadPhotoAsync.aspx/DeleteUploadedPhoto",
                    data: '{"filenameNoExt": "' + filename + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function () {
                        var divId = div.attr('id');
                        var number = divId.split('-')[1];

                        var img = div.find('img.upload-img');
                        img.attr('src', BlankImageSrc);
                        $('#imgBtn-' + number).hide();

                        var showcase = photoShowcases[number-1];
                        showcase.hasImage = false;                  
                    }
                });
            }
        }

        function dragOver(event, ui) {
            var imgOver = $(this).find('img.upload-img');
            if (imgOver == null) {
                return;
            }

            var overImgSrc = imgOver.attr('src');
            if (!isImageEmpty(overImgSrc)) {
                $(this).addClass('drag-hover');
            }
        }

        function dragOut(event, ui) {
            $(this).removeClass('drag-hover');
        }

        function handleCarDrop(event, ui) {
            var imgDroppedOn = $(this).find('img.upload-img');

            if (imgDroppedOn == null) {
                return;
            }

            // get src of the img dropped on
            var droppedOnImgSrc = imgDroppedOn.attr('src');

            if (!isImageEmpty(droppedOnImgSrc)) {
                var draggedImgSrc = ui.draggable.attr('src');
                ui.draggable.attr('src', droppedOnImgSrc);
                imgDroppedOn.attr('src', draggedImgSrc);
                $(this).removeClass('drag-hover');
            }
        }

        function submit() {
            var cars = new Array();
            var number;
            for (var i = 0; i < 16; ++i) {
                number = i + 1;
                var backImage = $('#img-' + number).attr('src');
                if (!isImageEmpty(backImage)) {
                    cars.push(extractFilename(backImage));
                }
            }

            if (cars.length == 0) {
                return;
            }

            var jsonText = JSON.stringify({ list: cars });

            $.ajax({
                type: "POST",
                url: "UploadPhotoAsync.aspx/Submit",
                data: jsonText,
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });

            window.location.replace($('#lblNextStepUrl').text());
        }

    </script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="cph1" runat="server">    
    <div id="post-ad-uploada" >      
        <table class="post-ad-steps">
            <tr>
                <td><span class="step-num other-step-num">1</span>基本信息</td>
                <td class="current-step"><span class="step-num current-step-num">2</span>添加照片</td>
                <td><span class="step-num other-step-num">3</span>预览发布</td>
            </tr>
        </table>   
        
        <div id="div-uploada">           
            <asp:FileUpload ID="fileUploader" runat="server" AllowMultiple="true" CssClass="fileUploader" onchange="processFiles(this.files)" />
            <asp:Label ID="lblUploadPhotoMessage" runat="server" CssClass="post-ad-validation" />
            
            <div class="clear"></div>

            <div id="showcase-divs">
                <div id="td-1" class="showcase">
                    <span id="imgBtn-1" class="del-span"></span>
                    <img id="img-1" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-1" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-2" class="showcase">
                    <span id="imgBtn-2" class="del-span"></span>
                    <img id="img-2" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-2" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-3" class="showcase">
                    <span id="imgBtn-3" class="del-span"></span>
                    <img id="img-3" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-3" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-4" class="showcase">
                    <span id="imgBtn-4" class="del-span"></span>
                    <img id="img-4" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-4" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>

                <div class="clear"></div>

                <div id="td-5" class="showcase">
                    <span id="imgBtn-5" class="del-span"></span>
                    <img id="img-5" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-5" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-6" class="showcase">
                    <span id="imgBtn-6" class="del-span"></span>
                    <img id="img-6" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-6" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-7" class="showcase">
                    <span id="imgBtn-7" class="del-span"></span>
                    <img id="img-7" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-7" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-8" class="showcase">
                    <span id="imgBtn-8" class="del-span"></span>
                    <img id="img-8" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-8" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>

                <div class="clear"></div>

                <div id="td-9" class="showcase">
                    <span id="imgBtn-9" class="del-span"></span>
                    <img id="img-9" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-9" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-10" class="showcase">
                    <span id="imgBtn-10" class="del-span"></span>
                    <img id="img-10" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-10" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-11" class="showcase">
                    <span id="imgBtn-11" class="del-span"></span>
                    <img id="img-11" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-11" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-12" class="showcase">
                    <span id="imgBtn-12" class="del-span"></span>
                    <img id="img-12" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-12" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>

                <div class="clear"></div>

                <div id="td-13" class="showcase">
                    <span id="imgBtn-13" class="del-span"></span>
                    <img id="img-13" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-13" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-14" class="showcase">
                    <span id="imgBtn-14" class="del-span"></span>
                    <img id="img-14" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-14" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-15" class="showcase">
                    <span id="imgBtn-15" class="del-span"></span>
                    <img id="img-15" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-15" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
                <div id="td-16" class="showcase">
                    <span id="imgBtn-16" class="del-span"></span>
                    <img id="img-16" src="../Images/space.gif" class="upload-img" />
                    <img id="prog-16" alt="uploading" src="../Images/uploading.gif" class="upload-progress" />
                </div>
            </div>

            <div id="help-div">
            
                <ul>
                    <li>上传至少一张照片</li>
                    <li>照片大小不超过8MB</li>
                    <li>第一张照片将被用作封面</li>
                    <li>可拖放照片改变顺序</li>
                </ul> 
            
            </div>

            <div class="clear"></div>

            <asp:Label ID="lblNextStepUrl" runat="server" ClientIDMode="Static" />

            <div id="next-step-btn">
                <asp:Label ID="btnSubmit" runat="server" Text="下一步" class="btnSubmit" ClientIDMode="Static" /> 
            </div>
        </div>
    </div>
</asp:Content>
